<template>
<AsyncCompent />
</template>

<script setup>
import * as Vue from 'vue';
import * as stores from '@/stores';
import * as VueRouter from 'vue-router';
import * as Ant from 'ant-design-vue';

import { loadModule } from 'vue3-sfc-loader';
import {defineAsyncComponent} from 'vue';
import {onBeforeRouteUpdate } from 'vue-router';

const domain = "https://gitee.com/454383818/mdnotes/raw/master/vue3.%E6%9C%8D%E5%8A%A1%E5%99%A8%E8%BF%94%E5%9B%9Esfc%E6%96%87%E6%A1%A3%E5%B9%B6%E5%8A%A0%E8%BD%BD.demo/server"

let fetchComponent =(apiUrl)=>{
    return defineAsyncComponent( async ()=>{
        const options = {
            /// 这儿加载需要使用的模块，
            moduleCache: { 
                vue: Vue,
                '@stores':stores,
                'vue-router':VueRouter,
                'ant-design-vue':Ant,
            },
            /// 这儿是去请求 服务端的 sfc 文件内容
            async getFile(url) {
                try{
                    let path = url.replace(/\.vue$/,'.txt').replace(/^\//,'');
                    let fetchUrl = `${domain}/${path}`;
                    console.log('asdfasdf',fetchUrl)
                    let response = await fetch(fetchUrl)
                    if(response.ok && response.status==200){
                        return await response.text()
                    }else{
                        throw new Error('load-error');
                    }
                }catch(err){
                    return `
                        <template>
                            <Result status="403" title="403" sub-title="Sorry, you are not authorized to access this page.">
                            </Result>
                        </template>
                        <script setup>
                            import {Result} from 'ant-design-vue';
                        <\/script>
                    `
                }
            },
            /// sfc 如果存在 style 标签，通过这儿加载到head 里
            addStyle(styleString,id) {
                    let style = document.createElement('style');
                    style.id=id;
                    style.className="vue-sfc-loader";
                    style.textContent = styleString;
                    const ref = document.head.getElementsByTagName('style')[0] || null;
                    document.head.insertBefore(style, ref);
            }
        };
        /// 通过 vue3-sfc-loader 将 string 转化为 vue 模块
        console.log(apiUrl);
        return loadModule(`${apiUrl}.vue`, options);
    })
}

let AsyncCompent = fetchComponent(window.location.href.split('/').reverse()[0]);

onBeforeRouteUpdate((to,from)=>{
    AsyncCompent = fetchComponent(to.path);
})
</script>